﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using Utility.Inspector;
using TerrainSystem;
using Utility.DataSystem;

namespace DataSystem
{
	public class TileSettingEditorWindow : SettingObjectEditorWindow<TileSettingObject>
	{
		protected override GUIContent TitleContent => new GUIContent ("地块设定");
		protected override string SettingPath => EditorConstants.RootPath_TileSettings;

		[MenuItem ("Settings/地块设定")]
		protected static void OpenWindow ()
		{
			OpenWindow<TileSettingEditorWindow> ();
		}

		[UnityEditor.Callbacks.OnOpenAsset (0)]
		protected static bool OnOpenAsset (int instId, int line)
		{
			return OnOpenAsset<TileSettingEditorWindow> (instId, line);
		}

		protected override void DrawSetting ()
		{
			Setting.prefab = EditorGUILayoutEX.ObjectField ("预制体", Setting.prefab, false);

			GUILayout.BeginHorizontal ();
			Setting.autoPrefab = EditorGUILayout.Toggle ("自动生成预制体", Setting.autoPrefab);
			GUILayout.FlexibleSpace ();
			if (Setting.autoPrefab)
			{
				if (GUILayout.Button ("创建"))
				{
					Setting.prefab = CreatePrefab (Setting);
				}
			}
			GUILayout.EndHorizontal ();
			if (Setting.autoPrefab)
			{
				var newModel = EditorGUILayoutEX.ObjectField ("模型", Setting.model, false);
				//if (newModel == null || PrefabUtility.GetPrefabAssetType (newModel) == PrefabAssetType.Model)
				{
					Setting.model = newModel;
				}
			}

			Setting.terrainLayer = EditorGUILayoutEX.EnumPopup ("地块层级", Setting.terrainLayer);

			Setting.canBuild = EditorGUILayout.Toggle ("可以建造", Setting.canBuild);

			Setting.surfaceHeight = EditorGUILayout.FloatField ("表面高度", Setting.surfaceHeight);
			
			Setting.color = EditorGUILayout.ColorField ("颜色",Setting.color);
			
			Setting.texture = EditorGUILayoutEX.ObjectField ("贴图", Setting.texture, false);

		}

		GameObject CreatePrefab (TileSettingObject setting)
		{
			GameObject go = new GameObject ();
			GameObject prefab = null;
			GameObject model = null;
			try
			{
				go.name = "Tile_" + setting.name;
				var tile = go.AddComponent<Tile> ();
				Tile.SetSetting (tile, setting);

				//model
				if (setting.model != null)
				{
					model = PrefabUtility.InstantiatePrefab (setting.model) as GameObject;
					model.transform.parent = go.transform;
					model.transform.localRotation = Quaternion.identity;
					model.transform.localPosition = Vector3.zero;
					model.transform.localScale = Vector3.one;
				}

				string path = "Assets/" + EditorConstants.RootPath_Prefab_Tile + go.name + ".prefab";
				Directory.CreateDirectory ($"{Application.dataPath}/{EditorConstants.RootPath_Prefab_Tile}");
				prefab = PrefabUtility.SaveAsPrefabAsset (go, path);
			}
			catch (System.Exception e)
			{
				throw (e);
			}
			finally
			{
				DestroyImmediate (go);
				DestroyImmediate (model);
			}

			return prefab;
		}
	}
}